"use client";

import { Header } from "@/sections/Header";
import { SectionHeader } from "@/components/SectionHeader";
import { BentoGrid } from "@/components/BentoGrid";
import { BentoCard } from "@/components/BentoCard";
import { useEffect, useState } from "react";
import { LoadingSpinner } from "@/components/ui/loading";
import Link from "next/link";
import { motion } from "framer-motion";

const containerVariants = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: {
      staggerChildren: 0.3
    }
  }
};

const itemVariants = {
  hidden: { y: 20, opacity: 0 },
  visible: {
    y: 0,
    opacity: 1,
    transition: {
      duration: 0.5
    }
  }
};

import { getBlogPosts, type BlogPost } from '@/lib/api';

export default function BlogPage() {


  const [blogPosts, setBlogPosts] = useState<BlogPost[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);
  const [selectedCategory, setSelectedCategory] = useState<string>('全部');

  // 定义fetchData函数，以便可以在组件中重用
  const fetchData = async () => {
    setIsLoading(true);
    setError(null);
    try {
      // 直接调用getBlogPosts，不再需要额外的超时处理
      const response = await getBlogPosts();
      
      // 检查API响应中是否有错误信息
      if (response?.meta?.error) {
        throw new Error(response.meta.error as string);
      }
      // 确保我们有一个数组，即使API返回结构不符合预期
      const posts = Array.isArray(response?.data) ? response.data : [];
      console.log('获取到博客文章:', posts.length);
      setBlogPosts(posts);
    } catch (error) {
      console.error('Error fetching blog data:', error);
      // 处理不同类型的错误，提供更友好的错误信息
      const err = error instanceof Error ? error : new Error(String(error));
      
      // 根据错误类型设置不同的错误信息
      if (err.name === 'TypeError' && err.message.includes('Failed to fetch')) {
        setError(new Error('网络连接失败，请检查您的网络连接或服务器状态'));
      } else if (err.message.includes('请求超时')) {
        setError(new Error('服务器响应超时，请稍后重试'));
      } else if (err.message.includes('API基础URL未配置')) {
        setError(new Error('系统配置错误，请联系管理员'));
      } else {
        setError(err);
      }
      
      setBlogPosts([]);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);


  const categories = ['全部', ...Array.from(new Set(blogPosts.map(post => post.category)))];
  const filteredPosts = selectedCategory === '全部' ? blogPosts : blogPosts.filter(post => post.category === selectedCategory);

  if (isLoading) {
    return (
      <div className="min-h-screen bg-indigo-950">
        <Header />
        <main className="container py-32">
          <div className="flex flex-col items-center justify-center gap-4">
            <LoadingSpinner className="size-12" />
            <p className="text-white/60">正在加载博客文章...</p>
          </div>
        </main>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-indigo-950">
        <Header />
        <main className="container py-32">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="flex flex-col items-center justify-center gap-6 text-center"
          >
            <div className="p-6 bg-red-400/10 rounded-2xl border border-red-400/20">
              <span className="text-4xl">⚠️</span>
            </div>
            <h2 className="text-2xl font-semibold text-red-300">
              加载失败：{error.message || '网络连接异常'}
            </h2>
            <p className="text-white/60 max-w-md">
              请检查网络连接后重试，若问题持续存在请联系管理员
            </p>
            <div className="flex gap-4 mt-4">
              <button
                onClick={() => {
                  setIsLoading(true);
                  setError(null);
                  fetchData();
                }}
                className="px-6 py-3 bg-red-400/20 text-red-300 rounded-xl hover:bg-red-400/30 transition-colors flex items-center gap-2"
              >
                <span>立即重试</span>
                <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
              </button>
              <a
                href="/"
                className="px-6 py-3 bg-white/10 text-white/80 rounded-xl hover:bg-white/20 transition-colors"
              >
                返回首页
              </a>
            </div>
          </motion.div>
        </main>
      </div>
    );
  }
  
  return (
    <motion.div 
      initial="hidden"
      animate="visible"
      variants={containerVariants}
      className="min-h-screen bg-indigo-950"
    >
      <Header />
      <main className="container py-32">
        <motion.div variants={itemVariants} className="will-change-transform px-4 sm:px-0">
          <SectionHeader
            eyebrow="博客文章"
            title="技术分享与思考"
            description="分享我在软件开发和内容创作领域的经验与见解"
          />
        </motion.div>

        <motion.div variants={itemVariants} className="mt-8 flex flex-wrap gap-3 justify-center px-4 sm:px-0">
          {categories.map((category) => (
            <button
              key={category}
              onClick={() => setSelectedCategory(category)}
              className={`px-4 py-2 rounded-full text-sm font-medium border
                ${selectedCategory === category
                  ? 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30'
                  : 'bg-white/5 text-white/60 border-white/10'}`}
            >
              {category}
            </button>
          ))}
        </motion.div>
        
        <motion.div variants={itemVariants} className="mt-8 sm:mt-16 px-4 sm:px-0">
          <BentoGrid className="max-w-4xl mx-auto grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">
            {filteredPosts.map((post) => (
              <motion.div
                key={post.documentId}
                variants={itemVariants}
                className="will-change-transform"
                whileHover={{ scale: 1.02 }}
                transition={{ type: "spring", stiffness: 300, damping: 20 }}
              >
                <Link href={`/blog/${post.slug}`} className="block">
                  <BentoCard
                    header={post.title}
                    description={post.description}
                    className="md:p-8 bg-gradient-to-r from-emerald-300/10 to-sky-400/10 hover:from-emerald-300/20 hover:to-sky-400/20 transition-all duration-300 hover:shadow-lg hover:shadow-emerald-300/5 rounded-2xl border border-white/10 select-text"
                  >
                    {post.bg_image && (
                      <div className="-mx-4 md:-mx-8 -mt-4 md:-mt-8 mb-4 rounded-t-2xl overflow-hidden">
                        <img 
                          src={`https://server.illli.cc${post.bg_image.url}`}
                          alt={post.title}
                          className="w-full h-48 object-cover"
                        />
                      </div>
                    )}
                    <div className="mt-3 md:mt-4 flex flex-row items-center justify-between gap-2">
                      <div className="text-emerald-300 text-xs font-medium px-2 py-1 bg-emerald-500/10 rounded-lg border border-emerald-500/10">
                        {post.category}
                      </div>
                      <div className="text-white/60 text-xs font-medium">
                        {post.data}
                      </div>
                    </div>
                  </BentoCard>
                </Link>
              </motion.div>
            ))}
          </BentoGrid>
        </motion.div>
      </main>
    </motion.div>
  );
}